package com.example.hotHub.service.impl;


import com.example.hotHub.model.NormalHotSearch;
import com.example.hotHub.service.ToutiaoHotPointService;
import com.example.hotHub.utils.RestTemplateUtil;
import com.example.hotHub.utils.SimpleMap;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ToutiaoHotPointServiceImpl implements ToutiaoHotPointService {

    @SneakyThrows
    @Override
    public List<NormalHotSearch> getHotPointList() {
        RestTemplateUtil restTemplateUtil = new RestTemplateUtil();
        SimpleMap response = restTemplateUtil.doGet("https://www.toutiao.com/hot-event/hot-board/?origin=toutiao_pc", null, null, SimpleMap.class);
        List<SimpleMap> list = response.getList("data", SimpleMap.class);
        List<NormalHotSearch> normalHotSearchList = new ArrayList<>();
        for (SimpleMap element : list) {
            String note = element.getString("Title");
            String url = element.getString("Url");
            String imageUrl = element.getMap("Image")
                    .getString("url");

            Integer hotValue = Integer.parseInt(String.valueOf(element.get("HotValue")));

            NormalHotSearch normalHotSearch = new NormalHotSearch()
                            .setTitle(note)
                            .setUrl(url)
                            .setHotValue(hotValue)
                            .setImageUrl(imageUrl)
                            .setDescribe(note);

            normalHotSearchList.add(normalHotSearch);
        }

        normalHotSearchList = normalHotSearchList.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());

        log.debug("成功爬取头条热点: {}", normalHotSearchList);

        return normalHotSearchList;
    }
}
